<template>
  <div id="message-send-box-wrapper" class="msg_shuru">
    <div class="send-header-bar msg_shuru_head">
      <el-popover placement="top" width="400" trigger="click">
        <div class="emojis">
          <div class="emojis_container">
            <div v-for="item in emojiName" class="emoji" :key="item" @click="chooseEmoji(item)">
              <img :src="emojiUrl + emojiMap[item]" style="width: 25px; height: 25px" />
            </div>
          </div>
          <!-- <div class="el-icon-chat-dot-round"></div> -->
        </div>
        <i class="iconfont icon-face" slot="reference" title="发表情"></i>
      </el-popover>

      <el-popover placement="top" width="400" trigger="click">
        <div class="emojis">
          <div v-for="item in emojiName1" class="emoji1" :key="item" @click="sendTextEmojiImg(item)">
            <img :src="emojiMap1[item]" style="width: 60px; height: 60px" />
          </div>
        </div>
        <div class="el-icon-chat-dot-round"></div>
        <i class="el-icon-picture" slot="reference" title="发表情"></i>
      </el-popover>

      <i class="el-icon-picture-outline" title="发图片" @click="handleSendImageClick"></i>
      <i class="el-icon-folder" title="发视频" @click="handleSendVideoClick"></i>
      <!-- <i class="el-icon-folder" title="发文件" @click="handleSendFileClick"></i> -->
      <!-- <i class="iconfont icon-custom" title="发自定义消息" @click="sendCustomDialogVisible = true"></i> -->
      <!-- <i class="iconfont icon-dice" title="投骰子" @click="sendDice"></i> -->
      <!-- <i class="rightPos el-icon-chat-dot-round"></i> -->
    </div>
    <el-dialog title="发自定消息" :visible.sync="sendCustomDialogVisible">
      <el-form label-width="100px">
        <el-form-item label="data">
          <el-input v-model="form.data"></el-input>
        </el-form-item>
        <el-form-item label="description">
          <el-input v-model="form.description"></el-input>
        </el-form-item>
        <el-form-item label="extension">
          <el-input v-model="form.extension"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="sendCustomDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="sendCustomMessage">确 定</el-button>
      </span>
    </el-dialog>

    <el-popover trigger="manual" v-model="showAtGroupMember" placement="top" style="max-height: 500px; overflow-y: scroll">
      <el-radio-group v-model="atUserID" style="display: flex; flex-decoration: column" v-for="member in memberList" :key="member.userID" @change="handleSelectAtUser">
        <el-radio :label="member.userID">{{
          member.nameCard || member.nick || member.userID
        }}</el-radio>
      </el-radio-group>

      <el-input slot="reference" type="textarea" :rows="4" resize="none" v-model="messageContent" class="text-input" @input="handleTextInput" @keydown.enter.native.prevent="handleEnter" @keydown.up.native.prevent="handleUp" @keydown.down.native.prevent="handleDown" @paste.native="pasting" />
    </el-popover>

    <input type="file" id="imagePicker" ref="imagePicker" accept=".jpg, .jpeg, .png, .gif" @change="sendImage" style="display: none" />
    <input type="file" id="videoPicker" ref="videoPicker" @change="sendVideo" accept=".mp4"   style="display: none"  />
    <input type="file" id="filePicker" ref="filePicker" @change="sendFile" style="display: none" />
    <div class="sendBtn">
      <el-button size="small" @click="closeChat">结束会话</el-button>
      <el-button size="small" type="primary" @click="sendTextMessage">发送</el-button>
    </div>

    <el-dialog title="识别到图片" :visible.sync="pasteshow" width="350px" center @close="pasteshow = false;pastepic.src = '';pastepic.file = null;">
      <div class="pastebox">
        <img :src="pastepic.src" alt="">
        <div class="pastebtn">
          <el-button @click="pasteshow = false;pastepic.src = '';pastepic.file = null;" size="small">Esc关闭</el-button>
          <el-button type="primary" size="small" @click="pasteenter()">Enter 发送</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters, mapState } from "vuex";
import {
  Form,
  FormItem,
  Input,
  Dialog,
  Popover,
  RadioGroup,
  Radio,
} from "element-ui";
import { emojiMap, emojiName, emojiUrl } from "../../../utils/emojiMap";
import { emojiMap1, emojiName1 } from "../../../utils/emoji2";
console.log(emojiMap1, emojiName1);
export default {
  name: "message-send-box",
  props: ["scrollMessageListToButtom", "text"],
  components: {
    ElInput: Input,
    ElForm: Form,
    ElFormItem: FormItem,
    ElDialog: Dialog,
    ElPopover: Popover,
    ElRadioGroup: RadioGroup,
    ElRadio: Radio,
  },
  data() {
    return {
      pastepic: {},
      pasteshow: false,
      messageContent: "",
      isSendCustomMessage: false,
      sendCustomDialogVisible: false,
      form: {
        data: "",
        description: "",
        extension: "",
      },
      emojiName1: emojiName1,
      emojiMap1: emojiMap1,
      file: "",
      emojiMap: emojiMap,
      emojiName: emojiName,
      emojiUrl: emojiUrl,
      showAtGroupMember: false,
      atUserID: "",
    };
  },

  computed: {
    ...mapGetters(["toAccount", "currentConversationType"]),
    ...mapState({
      memberList: (state) => state.group.currentMemberList,
    }),
  },
  methods: {
    pasting(e) {
      if (e.clipboardData.files[0]) {
        var file = e.clipboardData.files[0];
        this.pastepic.file = e.clipboardData.files[0];
        this.pastepic.src = window.URL.createObjectURL(file);
        this.pasteshow = true;
      }
    },
    pasteenter(e) {
      const message = this.tim.createImageMessage({
        to: this.toAccount,
        conversationType: this.currentConversationType,
        payload: {
          file: this.pastepic.file,
        },
        onProgress: (percent) => {
          this.$set(message, "progress", percent); // 手动给message 实例加个响应式属性: progress
        },
      });
      this.$store.commit("pushCurrentMessageList", message);
      this.tim
        .sendMessage(message)
        .catch((imError) => this.$message.error(imError.message));
      this.pastepic = {
        file: null,
        src: "",
      };
      this.pasteshow = false;
      
      this.$api.getim.sendImMessage({ im: this.toAccount, types: 1 });
    },
    closeChat() {
      // 关闭会话
      console.log("ASAAA", this.memberList);
      console.log("mkyttttt", this.toAccount);
      let AcountId = "C2C" + this.toAccount; //暂时只支持 C2C删除会话
      this.tim
        .deleteConversation(AcountId)
        .then(() => {
          this.$message({
            message: `会话${AcountId}删除成功!`,
            type: "success",
          });
          // this.popoverVisible = false;
          this.$store.commit("resetCurrentConversation");
          this.$store.commit("setHeaderShow", false);
        })
        .catch((error) => {
          this.$message.error(
            `会话${AcountId}删除失败!, error=${error.message}`
          );
          // this.popoverVisible = false;
        });
    },
    sendTextEmojiImg(item) {
      const message = this.tim.createTextMessage({
        to: this.toAccount,
        conversationType: this.currentConversationType,
        payload: { text: item },
      });

      this.$store.commit("pushCurrentMessageList", message);
      this.$bus.$emit("scroll-bottom");
      this.tim.sendMessage(message);
      this.$api.getim.sendImMessage({ im: this.toAccount, types: 0 });
    },
    handleTextInput(event) {
      if (
        event.slice(-1) === "@" &&
        this.currentConversationType === this.TIM.TYPES.CONV_GROUP &&
        this.memberList.length > 0
      ) {
        this.atUserID = this.memberList[0].userID;
        this.showAtGroupMember = true;
      } else {
        this.showAtGroupMember = false;
      }
    },

    handleSelectAtUser() {
      this.messageContent += this.atUserID + " ";
      this.showAtGroupMember = false;
    },
    handleUp() {
      const index = this.memberList.findIndex(
        (member) => member.userID === this.atUserID
      );
      if (index - 1 < 0) {
        return;
      }
      this.atUserID = this.memberList[index - 1].userID;
    },
    handleDown() {
      const index = this.memberList.findIndex(
        (member) => member.userID === this.atUserID
      );
      if (index + 1 >= this.memberList.length) {
        return;
      }
      this.atUserID = this.memberList[index + 1].userID;
    },
    handleEnter() {
      if (this.pasteshow == true) {
        this.pasteenter();
      } else if (this.showAtGroupMember) {
        this.handleSelectAtUser();
      } else {
        this.sendTextMessage();
      }
    },
    sendTextMessage() {
      if (
        this.messageContent === "" ||
        this.messageContent.trim().length === 0
      ) {
        this.messageContent = "";
        this.$message("不能发送空消息哦！");
        return;
      }
      const message = this.tim.createTextMessage({
        to: this.toAccount,
        conversationType: this.currentConversationType,
        payload: { text: this.messageContent },
      });
      this.$store.commit("pushCurrentMessageList", message);
      this.$bus.$emit("scroll-bottom");
      this.tim.sendMessage(message);
      this.messageContent = "";
      this.$api.getim.sendImMessage({ im: this.toAccount, types: 0 });
    },
    sendCustomMessage() {
      if (
        this.form.data.length === 0 &&
        this.form.description.length === 0 &&
        this.form.extension.length === 0
      ) {
        this.$message.warning("不能发送空消息");
        return;
      }
      const message = this.tim.createCustomMessage({
        to: this.toAccount,
        conversationType: this.currentConversationType,
        payload: {
          data: this.form.data,
          description: this.form.description,
          extension: this.form.extension,
        },
      });
      this.$store.commit("pushCurrentMessageList", message);
      this.tim.sendMessage(message);
      Object.assign(this.form, {
        data: "",
        description: "",
        extension: "",
      });
      this.sendCustomDialogVisible = false;
    },
    random(min, max) {
      return Math.floor(Math.random() * (max - min + 1) + min);
    },
    sendDice() {
      const message = this.tim.createCustomMessage({
        to: this.toAccount,
        conversationType: this.currentConversationType,
        payload: {
          data: "dice",
          description: String(this.random(1, 6)),
          extension: "",
        },
      });
      this.$store.commit("pushCurrentMessageList", message);
      this.tim.sendMessage(message);
    },
    chooseEmoji(item) {
      this.messageContent += item;
    },
    handleSendImageClick() {
      this.$refs.imagePicker.click();
    },
    handleSendFileClick() {
      this.$refs.filePicker.click();
    },
    handleSendVideoClick() {
      this.$refs.videoPicker.click();
    },
    sendImage() {
      const message = this.tim.createImageMessage({
        to: this.toAccount,
        conversationType: this.currentConversationType,
        payload: {
          file: document.getElementById("imagePicker"), // 或者用event.target
        },
        onProgress: (percent) => {
          this.$set(message, "progress", percent); // 手动给message 实例加个响应式属性: progress
        },
      });
      console.log(document.getElementById("imagePicker"));

      this.$store.commit("pushCurrentMessageList", message);
      this.tim
        .sendMessage(message)
        .catch((imError) => this.$message.error(imError.message));
      this.$refs.imagePicker.value = null;
      
      this.$api.getim.sendImMessage({ im: this.toAccount, types: 1 });
    },
    sendFile() {
      const message = this.tim.createFileMessage({
        to: this.toAccount,
        conversationType: this.currentConversationType,
        payload: {
          file: document.getElementById("filePicker"), // 或者用event.target
        },
        onProgress: (percent) => {
          this.$set(message, "progress", percent); // 手动给message 实例加个响应式属性: progress
        },
      });
      this.$store.commit("pushCurrentMessageList", message);
      this.tim
        .sendMessage(message)
        .catch((imError) => this.$message.error(imError.message));
      this.$refs.filePicker.value = null;
    },
    sendVideo() {
      const message = this.tim.createVideoMessage({
        to: this.toAccount,
        conversationType: this.currentConversationType,
        payload: {
          file: document.getElementById("videoPicker"), // 或者用event.target
        },
        onProgress: (percent) => {
          this.$set(message, "progress", percent); // 手动给message 实例加个响应式属性: progress
        },
      });
      this.$store.commit("pushCurrentMessageList", message);
      this.tim
        .sendMessage(message)
        .catch((imError) => this.$message.error(imError.message));
      this.$refs.videoPicker.value = null;
    },
  },
  watch: {
    text(val) {
      if (val) {
        this.messageContent = this.messageContent + val;
      }
    },
  },
};
</script>

<style  lang='less'>
.msg_shuru {
  background-color: #fff;
  position: relative;
  min-height: 182px;
  padding: 0 !important;
}
.msg_shuru_gn {
  position: relative;
  display: flex;
  justify-content: flex-start;
  span {
    position: absolute;
  }
  > div {
    width: 40px;
    height: 40px;
    color: #b7bac3;
    text-align: center;
    line-height: 40px;
  }
}
.msg_shuru_head {
  display: flex;
  border-top: 1px solid #f7f9fc;
  // border-bottom: 1px solid #ddd;
  align-items: center;
  padding: 5px 20px;
  color: #c3c6cd;
  position: relative;

  .prover {
    position: absolute;
    top: -300px;
    height: 302px;
    border: 1px solid #ddd;
    width: 482px;
    text-align: left;
    overflow: auto;
    background: #fff;
    z-index: 20;
    > span {
      display: inline-block;
      width: 80px;
      height: 80px;
      margin: 5px;
    }
  }
}
#message-send-box-wrapper {
  position: relative;
  width: 100%;
  bottom: 0;
  left: 0;
  padding: 12px;
  box-sizing: border-box;
}
.emojis {
  height: 160px;
  border-bottom: 1px solid #eeeeee;
  box-sizing: border-box;
  display: flex;
  // flex-direction: column;
  flex-wrap: wrap;
  overflow-y: scroll;
}
.emojis_container {
  display: flex;
  flex-wrap: wrap;
  // justify-content: space-around;
  padding-left: 10px;
}
.emoji {
  height: 28px;
  width: 28px;
  padding: 2px 3px 3px 2px;
  box-sizing: border-box;
}
.emoji1 {
  height: 60px;
  width: 60px;
  padding: 2px 3px 3px 2px;
  box-sizing: border-box;
}
.btn-send {
  position: absolute;
  bottom: 20px;
  right: 40px;
}
.send-header-bar i {
  cursor: pointer;
  font-size: 1.4rem;
  color: gray;
  margin: 0 6px;
}
.send-header-bar i:hover {
  color: #000;
}
.text-input textarea {
  background-color: transparent;
  border: none;
}

.sendBtn {
  display: flex;
  width: 100%;
  justify-content: space-between;
  padding: 0 12px;
  // height: 50px;
}

.rightPos {
  position: absolute;
  right: 0;
}
</style>
